<template>
  <Form ref="formRef" :model="formParams">
    <Row>
      <Col span="4">
        <FormItem label="院区" prop="areaID">
          <Select v-model="formParams.areaID" style="width: 200px" @on-change="areaChg">
            <Option v-for="item in area" :value="item.areaID" :key="item.areaID">{{
              item.name
            }}</Option>
          </Select>
        </FormItem>
      </Col>
      <Col span="4">
        <FormItem label="科室" prop="categoryID">
          <TreeSelect
            :data="treeList.data"
            @on-change="treeChg"
            v-model="formParams.categoryID"
            style="width: 200px"
          >
          </TreeSelect>
        </FormItem>
      </Col>
      <Col span="8">
        <FormItem label="结算日期">
          <el-date-picker
            v-model="settlementDate"
            type="daterange"
            :clearable="false"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </FormItem>
      </Col>
      <Col span="3">
        <Space style="margin-left: 20px">
          <Button type="primary" icon="md-search" @click="goSearch(false)">查询</Button>
          <Button type="dashed" icon="md-refresh" @click="clear">重置</Button>
        </Space>
      </Col>
    </Row>
  </Form>
  <Row style="padding-top: 30px">
    <Col span="24" style="margin-bottom: 20px">
      <div class="chart-container">
        <el-card style="width: 33%">
          <div class="chart-header">
            <h3>盈亏科室分布</h3>
          </div>
          <div style="width: 100%; height: 350px" id="line1"></div>
        </el-card>
        <el-card style="width: 33%">
          <div class="chart-header">
            <h3>盈余科室TOP5</h3>
          </div>
          <div style="width: 100%; height: 350px" id="line2"></div>
        </el-card>
        <el-card style="width: 33%">
          <div class="chart-header">
            <h3>亏损科室TOP5</h3>
          </div>
          <div style="width: 100%; height: 350px" id="line3"></div>
        </el-card>
      </div>
    </Col>
  </Row>

  <div class="header-container">
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane label="全部科室" name="0"></el-tab-pane>
      <el-tab-pane label="结余科室" name="1"></el-tab-pane>
      <el-tab-pane label="超支科室" name="-1"></el-tab-pane>
    </el-tabs>
    <el-button type="primary" @click="handleExport">
      导出
      <el-icon class="el-icon--right">
        <Download />
      </el-icon>
    </el-button>
  </div>
  <el-table :data="tableData" border style="width: 100%">
    <el-table-column prop="name" align="center" label="科室" width="120" />
    <el-table-column prop="total" align="center" label="总费用(万元)" sortable />
    <el-table-column prop="remain" align="center" label="结余" sortable />
    <el-table-column prop="cnt" align="center" label="病例数" sortable>
      <template #default="scope">
        <el-button type="primary" link @click="handleDetail(scope.row)">{{
          scope.row.cnt
        }}</el-button>
      </template>
    </el-table-column>
    <el-table-column v-if="policy === 'DIP'" align="center" prop="zqz" label="总权重" sortable />
    <el-table-column v-if="policy === 'DRG'" align="center" prop="zqz" label="总分值" sortable />
    <el-table-column prop="cjfy" align="center" label="次均费用" sortable />
    <el-table-column prop="cjjy" align="center" label="次均结余" sortable />
    <el-table-column prop="yzb" align="center" label="药占比" sortable />
    <el-table-column prop="hzb" align="center" label="耗占比" sortable />
    <el-table-column prop="jczb" align="center" label="检查占比" sortable />
    <el-table-column prop="jyzb" align="center" label="检验占比" sortable />
    <el-table-column prop="max_dss_grp" align="center" label="超支最大诊组" show-overflow-tooltip>
      <template #default="scope">
        <el-button type="primary" link @click="handleDetail(scope.row)">{{
          scope.row.max_dss_grp
        }}</el-button>
      </template>
    </el-table-column>
    <el-table-column prop="max_mdc_grp" align="center" label="超支最高医疗组" show-overflow-tooltip>
      <template #default="scope">
        <el-button type="primary" link @click="handleDetail(scope.row)">{{
          scope.row.max_mdc_grp
        }}</el-button>
      </template>
    </el-table-column>
    <el-table-column prop="max_dc" align="center" label="超支最多医生" show-overflow-tooltip>
      <template #default="scope">
        <el-button type="primary" link @click="handleDetail(scope.row)">{{
          scope.row.max_dc
        }}</el-button>
      </template>
    </el-table-column>
    <el-table-column fixed="right" align="center" label="操作" width="120">
      <template #default="scope">
        <el-button type="primary" link @click="handleDetail(scope.row)">查看详情</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="pagination-container">
    <el-pagination
      v-model:current-page="formParams.pageNo"
      v-model:page-size="formParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>
<script setup>
import * as echarts from 'echarts'
import { onActivated, onMounted, onBeforeUnmount } from 'vue'
import { Download, CaretTop, CaretBottom } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
const router = useRouter()

import { useCommonStore } from '@/stores/common.js'
const commonStore = useCommonStore()
const policy = ref('')
policy.value = commonStore.getPolicy()

import moment from 'moment'
import http from '@/util/http1'
const formParams = ref({
  startDate: '',
  endDate: '',
  areaID: '1',
  categoryID: '',
  type: '0',
  pageNo: 1,
  pageSize: 10,
})

const total = ref(0)

const handleExport = () => {
  const params = Object.assign({}, formParams.value)
  http
    .post('/Settlement/List/Export', params, {
      responseType: 'blob',
    })
    .then((res) => {
      const blob = new Blob([res.data])
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob)
      downloadElement.href = href
      downloadElement.download = '科室信息.xlsx'
      document.body.appendChild(downloadElement)
      downloadElement.click()
      document.body.removeChild(downloadElement)
      window.URL.revokeObjectURL(href)
    })
}
const handleSizeChange = (val) => {
  formParams.value.pageSize = val
  goSearch(true)
}

const handleCurrentChange = (val) => {
  formParams.value.pageNo = val
  goSearch(true)
}

const handleDetail = (row) => {
  router.push({
    path: '/Statistic/item/index',
    query: {
      type: '科室',
      name: row.name,
      areaID: formParams.value.areaID,
      categoryID: formParams.value.categoryID,
      startDate: moment(settlementDate.value[0]).format('YYYY-MM-DD 00:00:00'),
      endDate: moment(settlementDate.value[1]).format('YYYY-MM-DD 00:00:00'),
      data: row.code,
    },
  })
}

const handleTabChange = (tab) => {
  formParams.value.type = tab
  goSearch(true)
}

const activeTab = ref('0')
const tableData = ref([
  {
    dept: '神经外科',
    totalAmount: 1234.56,
    surplus: 234.56,
    caseCount: 156,
    id: 111,
    trend: 'up',
    totalScore: 789.12,
    avgCost: 7912.34,
    avgSurplus: 1503.59,
    drugRatio: '23.45%',
    materialRatio: '15.67%',
    inspectRatio: '12.34%',
    testRatio: '8.90%',
    maxDiagnosis: '颅内肿瘤切除术',
    maxDeptGroup: '神经系统疾病',
    maxDoctor: '张三',
  },
])

const area = ref([])
const initArea = () => {
  http.get('/Basic/Area/ListByUser', {}).then((response) => {
    area.value = response.data
    areaChg(response.data[0].areaID)
  })
}
initArea()

const areaChg = (areaID) => {
  formParams.value.areaID = areaID
  initTreeList()
}

let treeList = reactive({ data: [] })
const initTreeList = () => {
  http.get('/Basic/Category/TreeList?areaID=' + formParams.value.areaID, {}).then((response) => {
    treeList.data = formatTreeData(response.data)
  })
}

const formatTreeData = (data) => {
  return data.map((item) => ({
    title: item.title,
    value: item.categoryID,
    expand: true,
    children: item.children ? formatTreeData(item.children) : null,
  }))
}

const treeChg = (value) => {
  console.log(value)
}

let lineChart1 = null
let lineChart2 = null
let lineChart3 = null

const lineList1 = ref({
  series: [
    {
      type: 'pie',
      radius: ['50%', '70%'],
      label: {
        show: true,
        formatter: '{b}\n{c}个',
      },
      data: [
        { value: 38, name: '盈余科室' },
        { value: 12, name: '亏损科室' },
      ],
    },
  ],
})

const lineList2 = ref({
  series: [
    {
      type: 'bar',
      data: [90, 75, 65, 45, 35],
      label: {
        show: true,
        position: 'right',
        formatter: '{c}万元',
      },
      barWidth: 30,
      barMaxWidth: 30,
    },
  ],
  yAxis: ['神经外科', '神经内科', '骨外科', '消化内科', '肾内科'],
})

const lineList3 = ref({
  series: [
    {
      type: 'bar',
      data: [85, 75, 65, 45, 35],
      label: {
        show: true,
        position: 'right',
        formatter: '{c}万元',
      },
      barWidth: 30,
      barMaxWidth: 30,
    },
  ],
  yAxis: ['神经外科', '神经内科', '骨外科', '消化内科', '肾内科'],
})

const initCharts = () => {
  initLine1()
  initLine2()
  initLine3()
}

const initLine1 = () => {
  const line1 = document.getElementById('line1')
  lineChart1 = echarts.init(line1)
  updateLine1Chart()
}

const initLine2 = () => {
  const line2 = document.getElementById('line2')
  lineChart2 = echarts.init(line2)
  updateLine2Chart()
}

const initLine3 = () => {
  const line3 = document.getElementById('line3')
  lineChart3 = echarts.init(line3)
  updateLine3Chart()
}

const updateLine1Chart = () => {
  if (!lineChart1) return

  const option1 = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}个 ({d}%)',
    },
    legend: {
      orient: 'horizontal',
      right: '10%',
      top: '5%',
      data: ['盈余科室', '亏损科室'],
    },
    series: lineList1.value.series || [],
  }
  lineChart1.setOption(option1)
}

const updateLine2Chart = () => {
  if (!lineChart2) return

  const option2 = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '18%',
      right: '15%',
    },
    xAxis: {
      type: 'value',
      position: 'bottom',
      name: '金额（万元）',
      nameLocation: 'middle',
      nameGap: 35,
      nameTextStyle: {
        align: 'left',
        verticalAlign: 'right',
        padding: [0, 0, 0, 100],
      },
    },
    yAxis: {
      type: 'category',
      data: lineList2.value.yAxis,
      axisLine: { show: false },
      axisTick: { show: false },
    },
    series: lineList2.value.series,
  }
  lineChart2.setOption(option2)
}

const updateLine3Chart = () => {
  if (!lineChart3) return

  const option3 = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '18%',
      right: '15%',
    },
    xAxis: {
      type: 'value',
      position: 'bottom',
      name: '金额（万元）',
      nameLocation: 'middle',
      nameGap: 35,
      nameTextStyle: {
        align: 'left',
        verticalAlign: 'right',
        padding: [0, 0, 0, 100],
      },
    },
    yAxis: {
      type: 'category',
      data: lineList3.value.yAxis,
      axisLine: { show: false },
      axisTick: { show: false },
    },
    series: lineList3.value.series,
  }
  lineChart3.setOption(option3)
}

onMounted(() => {
  initCharts()
})

const formRef = ref(null)
const settlementDate = ref([])
settlementDate.value = [moment().subtract(1, 'year').toDate(), moment().toDate()]
const clear = () => {
  settlementDate.value = [moment().subtract(1, 'year').toDate(), moment().toDate()]
  formParams.value.pageNo = 1
  formRef.value.resetFields()
}
const goSearch = async (isFlag = false) => {
  if (settlementDate.value && settlementDate.value.length) {
    formParams.value.startDate = moment(settlementDate.value[0]).format('YYYY-MM-DD HH:mm:ss')
    formParams.value.endDate = moment(settlementDate.value[1]).format('YYYY-MM-DD HH:mm:ss')
  } else {
    formParams.value.startDate = formParams.value.endDate = ''
  }

  const params = Object.assign({}, formParams.value)

  const baseParams = {
    startDate: params.startDate,
    endDate: params.endDate,
    areaID: params.areaID,
    categoryID: params.categoryID,
  }

  const listParams = {
    ...baseParams,
    type: params.type,
    pageNo: params.pageNo,
    pageSize: params.pageSize,
  }

  if (isFlag) {
    const res1 = await http.post('/Statistic/Category/PageList', toRaw(listParams))
    tableData.value = res1.data.list || []
    total.value = res1.data.total || 0
    return
  }

  try {
    const [res1, res2] = await Promise.all([
      http.post('/Statistic/Category/PageList', toRaw(listParams)),
      http.post('/Statistic/Category/Part1', toRaw(baseParams)),
    ])

    tableData.value = res1.data.list || []
    total.value = res1.data.total || 0

    lineList1.value.series[0].data[0].value = res2.data.yy
    lineList1.value.series[0].data[1].value = res2.data.ks

    lineList2.value.yAxis = res2.data.bar1.map((item) => item.categoryName) || []
    lineList2.value.series[0].data = res2.data.bar1.map((item) => item.amount) || []

    lineList3.value.yAxis = res2.data.bar2.map((item) => item.categoryName) || []
    lineList3.value.series[0].data = res2.data.bar2.map((item) => item.amount) || []

    updateLine1Chart()
    updateLine2Chart()
    updateLine3Chart()
  } catch (error) {
    console.error('数据获取失败:', error)
  }
}
onActivated(() => {
  goSearch(false)
})

window.addEventListener('resize', () => {
  lineChart1?.resize()
  lineChart2?.resize()
  lineChart3?.resize()
})

onBeforeUnmount(() => {
  lineChart1?.dispose()
  lineChart2?.dispose()
  lineChart3?.dispose()
})
</script>

<style lang="less" scoped>
:deep(.el-button--link:focus) {
  outline: none;
  border: none;
  box-shadow: none;
}
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  :deep(.el-tabs__header) {
    margin-bottom: 0;
  }
}
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 10px;
}
.chart-container {
  display: flex;
  justify-content: space-between;
}
.el-date-range-picker {
  width: 680px !important;
}
.el-date-range-picker .el-picker-panel__body {
  min-width: 640px;
}

.custom-year-cell {
  padding: 4px;
  text-align: center;
}

.cell-buttons {
  display: flex;
  gap: 4px;
  justify-content: center;
  margin-top: 4px;
}

.cell-buttons .el-button {
  flex: 1;
  min-width: 60px;
}

/* 调整日期选择器的宽度以适应按钮 */
.el-picker-panel {
  min-width: 200px !important;
}

.half-year-cell {
  padding: 8px 0;
  text-align: center;
}

.year-text {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.half-year-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
}

.half-year-buttons .el-button {
  flex: 1;
  margin: 0;
  padding: 4px 0;
}

.half-year-buttons .divider {
  width: 1px;
  height: 16px;
  background-color: #dcdfe6;
  margin: 0 4px;
}

.half-year-buttons .active {
  color: var(--el-color-primary);
  font-weight: bold;
}

/* 调整日期选择器的宽度 */
.el-picker-panel.el-date-picker {
  min-width: 280px !important;
}

.el-year-table td {
  padding: 8px 0;
}
</style>
